﻿//
// Copyright © MixModes Inc. 2011
//

using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interactivity;
using MixModes.Phone.Synergy.Framework;

namespace MixModes.Phone.Synergy.Triggers
{
    /// <summary>
    /// Event trigger that executes a command
    /// </summary>
    public class EventToCommand : TriggerAction<Control>
    {        
        /// <summary>
        /// Command property
        /// </summary>
        public static DependencyProperty CommandProperty = DependencyProperty.Register("Command", 
                                                                                       typeof (Binding),
                                                                                       typeof (EventToCommand),
                                                                                       new PropertyMetadata(null, OnCommandChanged));        

        /// <summary>
        /// Command parameter property
        /// </summary>
        public static DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter",
                                                                                                typeof(Binding),
                                                                                                typeof(EventToCommand),
                                                                                                new PropertyMetadata(null, OnCommandParameterChanged));

        /// <summary>
        /// Gets or sets a value indicating whether event args should be passed to command
        /// </summary>
        /// <value>
        /// 	<c>true</c> if event args should be passed to command; otherwise, <c>false</c>.
        /// </value>
        public bool PassEventArgsToCommand
        {
            get; set; 
        }

        /// <summary>
        /// Command.
        /// </summary>
        /// <returns>Command</returns>
        public Binding Command
        {
            get
            {
                return GetValue(CommandProperty) as Binding;                
            }
            set
            {
                SetValue(CommandProperty, value);                
            }
        }

        /// <summary>
        /// Command parameter.
        /// </summary>
        /// <returns>Command parameter</returns>
        public Binding CommandParameter
        {
            get
            {
                return GetValue(CommandParameterProperty) as Binding;                
            }
            set
            {
                SetValue(CommandParameterProperty, value);                
            }
        }

        /// <summary>
        /// Called after the action is attached to an AssociatedObject.
        /// </summary>
        protected override void OnAttached()
        {
            base.OnAttached();

            if (Command != null)
            {
                _observableCommandBinding.Attach(Command, AssociatedObject);
            }
        }

        /// <summary>
        /// Invokes the action.
        /// </summary>
        /// <param name="parameter">The parameter to the action. If the Action does not require a parameter, the parameter may be set to a null reference.</param>
        protected override void Invoke(object parameter)
        {
            ICommand command = _observableCommandBinding.Value as ICommand;

            if ((AssociatedObject == null) ||
                (!AssociatedObject.IsEnabled) ||
                (command == null))
            {
                return;
            }

            object commandParameter = CommandParameterProperty;

            if ((CommandParameter == null) && (PassEventArgsToCommand))
            {
                commandParameter = parameter;
            }

            if (command.CanExecute(commandParameter))
            {
                command.Execute(commandParameter);
            }
        }

        /// <summary>
        /// Called when command binding has changed
        /// </summary>
        /// <param name="d">The d.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            EventToCommand eventToCommand = d as EventToCommand;
            
            if (eventToCommand == null)
            {
                return;
            }

            eventToCommand._observableCommandBinding.Detach();
            
            if ((e.NewValue != null) && (eventToCommand.AssociatedObject != null))
            {
                eventToCommand._observableCommandBinding.Attach(eventToCommand.Command, eventToCommand.AssociatedObject);
            }
        }

        /// <summary>
        /// Called when command parameter binding has changed
        /// </summary>
        /// <param name="d">The d.</param>
        /// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
        private static void OnCommandParameterChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            EventToCommand eventToCommand = d as EventToCommand;

            if (eventToCommand == null)
            {
                return;
            }

            eventToCommand._observableCommandParameterBinding.Detach();
            
            if ((e.NewValue != null) && (eventToCommand.AssociatedObject != null))
            {
                eventToCommand._observableCommandParameterBinding.Attach(eventToCommand.Command, eventToCommand.AssociatedObject);
            }
        }
        
        // Private members
        private readonly ObservableBinding _observableCommandBinding = new ObservableBinding();
        private readonly ObservableBinding _observableCommandParameterBinding = new ObservableBinding();
    }
}
